import 'package:flutter/services.dart';
import 'channel_error_handler.dart';

/// 数据通信Channel - 负责数据传递
/// 处理用户信息、设备信息、应用配置等数据通信
class DataChannel {
  static const MethodChannel _channel = MethodChannel('data_channel');

  /// 设置iOS端主动返回数据处理
  static void setDataChannelHandler(Function(Map<String, dynamic> data) callback) {
    _channel.setMethodCallHandler((call) async {
      try {
        final nativeData = Map<String, dynamic>.from(call.arguments);
        callback(nativeData);
        final page = nativeData['page'] as String?;
        final action = nativeData['action'] as String?;
        final message = nativeData['message'] as String?;
        print('📱 [数据Channel] 处理iOS数据 - 页面: $page, 动作: $action, 消息: $message');
      } catch (e) {
        print('❌ [数据Channel] 数据类型转换失败: $e');
      }
    });
  }

  /// 发送用户信息给iOS
  static Future<Map<String, dynamic>> sendUserInfo(Map<String, dynamic> userInfo) async {
    try {
      final result = await _channel.invokeMethod('sendUserInfo', userInfo);
      final response = Map<String, dynamic>.from(result);
      return response;
    } on PlatformException catch (e) {
      ChannelErrorHandler.handleError(e, '发送用户信息', 'DataChannel');
      rethrow;
    }
  }

  /// 获取设备信息
  static Future<Map<String, dynamic>> getDeviceInfo() async {
    try {
      final result = await _channel.invokeMethod('getDeviceInfo');
      final response = Map<String, dynamic>.from(result);
      return response;
    } on PlatformException catch (e) {
      ChannelErrorHandler.handleError(e, '获取设备信息', 'DataChannel');
      rethrow;
    }
  }

  /// 获取应用信息
  static Future<Map<String, dynamic>> getAppInfo() async {
    try {
      final result = await _channel.invokeMethod('getAppInfo');
      final response = Map<String, dynamic>.from(result);
      return response;
    } on PlatformException catch (e) {
      ChannelErrorHandler.handleError(e, '获取应用信息', 'DataChannel');
      rethrow;
    }
  }

  /// 发送配置数据
  static Future<Map<String, dynamic>> sendConfigData(Map<String, dynamic> configData) async {
    try {
      final result = await _channel.invokeMethod('sendConfigData', configData);
      final response = Map<String, dynamic>.from(result);
      return response;
    } on PlatformException catch (e) {
      ChannelErrorHandler.handleError(e, '发送配置数据', 'DataChannel');
      rethrow;
    }
  }

  /// 发送分析数据
  static Future<Map<String, dynamic>> sendAnalyticsData(Map<String, dynamic> analyticsData) async {
    try {
      final result = await _channel.invokeMethod('sendAnalyticsData', analyticsData);
      final response = Map<String, dynamic>.from(result);
      return response;
    } on PlatformException catch (e) {
      ChannelErrorHandler.handleError(e, '发送分析数据', 'DataChannel');
      rethrow;
    }
  }
}
